import {ipcMain} from 'electron'
import {doDownload} from "./download";

export function loadListener(app) {
    const ipc = ipcMain;

    // 用于监听获取程序目录方法
    ipc.on('getAppPath', function (event, arg) {
        event.sender.send('InitAppPath', app.getAppPath());
    });

    // 用于监听获取用户下载目录方法
    ipc.on('getUserDownloadPath', function (event, arg) {
        event.sender.send('InitUserDownloadPath', app.getPath('downloads'));
    });

    ipc.on('startDownloadTask', function (event, taskDesc, task) {
        addTasksMap(taskDesc, task);

        doDownload(taskDesc, task, event);
    });

    ipc.on('stopDownloadTask', function(event, task){
        console.log(task);

        stopTasksMap(task);
    });
}

function addTasksMap(taskDesc, task){
    global.tasksMap[''+task.taskId] = {
        task: task,
        taskDesc: taskDesc,
        status: 'start'
    };
}

function stopTasksMap(task){
    if(global.tasksMap[''+task.taskId]){
        global.tasksMap[''+task.taskId].status = 'stop';
    } else {
        setTimeout(()=>{
            stopTasksMap(task);
        }, 100);
    }
}